package com.mooc.lib_ui_common.widget.bottom

import android.content.res.AssetManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mooc.lib_base_application.BaseApplication
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.lang.reflect.Type
import java.util.*

class AppConfig {

    companion object{
        var sDestConfig: HashMap<String, Destination>? = null
        var sBottomBar: BottomBar? = null
        fun getBottomBarConfig(): BottomBar? {
            if (sBottomBar == null) {
                val content = parseFile("main_tabs_config.json")
                sBottomBar = Gson().fromJson(content, BottomBar::class.java)
            }
            return sBottomBar
        }
        fun getDestConfig(): HashMap<String, Destination>? {
            if (sDestConfig == null) {
                val content: String = parseFile("destination.json")!!
                val stringStringMap: Type = object : TypeToken<HashMap<String, Destination>?>() {}.type
                sDestConfig = Gson().fromJson(
                    content,stringStringMap)
            }
            return sDestConfig
        }
        fun parseFile(fileName: String): String? {
            val assets: AssetManager = BaseApplication.instance!!.getAssets()
            var `is`: InputStream? = null
            var br: BufferedReader? = null
            val builder = StringBuilder()
            try {
                `is` = assets.open(fileName)
                br = BufferedReader(InputStreamReader(`is`))
                var line: String? = null
                while (br.readLine().also { line = it } != null) {
                    builder.append(line)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    `is`?.close()
                    br?.close()
                } catch (e: Exception) {
                }
            }
            return builder.toString()
        }
    }
}